package com.dsbj.mp.icardservice.utils.jwt;

import com.dsbj.mp.icardservice.model.MpUser;
import com.dsbj.mp.icardservice.utils.Constants;
import com.dsbj.mp.icardservice.utils.jwt.exception.JwtIllegalArgumentException;
import com.dsbj.mp.icardservice.utils.jwt.exception.JwtSignatureException;
import com.dsbj.mp.icardservice.utils.jwt.exception.JwtTokenExpiredException;
import com.dsbj.mp.icardservice.webserviceclient.dsbjpmc.WxUser;
import com.dsbj.starter.redis.utils.MultiRedisHelper;
import com.dsbj.starter.redis.utils.RedisHelper;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * @version 2017-10-27
 */
@Configuration
public class UserAuthUtil {

	@Value("${jwt.pub-key.path}")
	private String pubKeyPath;

	@Autowired
	private MultiRedisHelper multiRedisHelper;

	public IJWTInfo getInfoFromToken(String token) throws Exception {
		try {
			return JWTHelper.getInfoFromToken(token, pubKeyPath);
		} catch (ExpiredJwtException ex) {
			throw new JwtTokenExpiredException("User token expired!");
		} catch (SignatureException ex) {
			throw new JwtSignatureException("User token signature error!");
		} catch (IllegalArgumentException ex) {
			throw new JwtIllegalArgumentException("User token is null or empty!");
		} catch (MalformedJwtException ex) {
			throw new MalformedJwtException("User token is not corect");
		}
	}

	/**
	 * 根据token获取用户信息。
	 * 该方法从redis缓存中获取token信息。
	 * @param token
	 * @return
	 */
	public MpUser getUserInfoFromToken(String token) {
		return (MpUser) multiRedisHelper.get(token, Constants.REDISDB_ACCESS_TOKEN);
	}
}
